package com.iot.commonutils.utils;

import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * @author 孟繁森
 * @date 2021/3/11 16:49
 */
public class HttpContextUtils {
    /**
     * 返回HttpServletRequest对象
     * @return
     */
    public static HttpServletRequest getHttpServletRequest(){
        ServletRequestAttributes servletRequestAttributes =(ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        return servletRequestAttributes.getRequest();
    }

    /**
     * 返回HttpServletResponse对象
     * @return
     */
    public static HttpServletResponse getHttpServletResponse(){
        ServletRequestAttributes servletRequestAttributes =(ServletRequestAttributes)RequestContextHolder.getRequestAttributes();
        return servletRequestAttributes.getResponse();
    }

    /**
     * 判断是否是ajax请求
     * @return
     */
    public static boolean isAjax(){
        HttpServletRequest httpRequest = getHttpServletRequest();
        String requestHeader = httpRequest.getHeader("X-Requested-With");
        return "XMLHttpRequest".equals(requestHeader);
    }

    /**
     * 返回服务器的访问地址 协议+ip+端口
     * @return
     */
    public static String getHostUrl(){
        String protocol = getHttpServletRequest().getProtocol();
        String localAddr = getHttpServletRequest().getLocalAddr();
        int serverPort = getHttpServletRequest().getLocalPort();
        return protocol + localAddr + String.valueOf(serverPort);
    }



}
